<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>4_生命周期(新)_getSnapshotBeforeUpdate</title>
    <!-- 引入 react核心库 -->
    <script type="text/javascript" src="../js/17.0.1/react.development.js"></script>
    <!-- 引入 react-dom 用于支持操作DOM -->
    <script type="text/javascript" src="../js/17.0.1/react-dom.development.js"></script>
    <!-- 引入 babel 用于将 jsx转为 js -->
    <script type="text/javascript" src="../js/17.0.1/babel.min.js"></script>
</head>
<body>
<div id="test"></div>
<script type="text/babel">
    class Sum extends React.Component {

        // 构造器
        constructor(props) {
            console.log("组件构造器执行 ==== constructor");
            super(props);
            // 初始化状态
            this.state = {count: 0}
        }

        // +1按钮回调
        add = () => {
            const {count} = this.state;
            this.setState({count: count + 1});
        }

        death = () => {
            console.log("卸载组件 ==== death");
            ReactDOM.unmountComponentAtNode(document.getElementById("test"));
        }

        force = () => {
            console.log("强制更新组件 ==== force");
            this.forceUpdate();
        }


        // 组件挂载完毕的钩子
        componentDidMount() {
            console.log("组件挂载完毕 === componentDidMount");
        }

        // 组件将要卸载的钩子
        componentWillUnmount() {
            console.log("组件将要卸载 === componentWillUnmount");
        }

        // 控制组件更新的 “阀门”
        shouldComponentUpdate() {
            console.log("组件是否将要被更新 === shouldComponentUpdate");
            return true;
        }

        // 在更新之前获取快照
        getSnapshotBeforeUpdate() {
            console.log(" === getSnapshotBeforeUpdate");
            return "hello";
        }

        // 组件更新完毕的钩子
        /**
         *
         * @param preProps      先前的 props
         * @param preState      先前的 state
         * @param snapshotValue 获取的快照值
         */
        componentDidUpdate(preProps, preState, snapshotValue) {
            console.log(preProps, preState, snapshotValue)
            console.log("组件更新完毕 === comonentDidUpdate");
        }

        render() {
            console.log("渲染组件 === render")
            const {count} = this.state;
            return (
                <div>
                    <h2>当前求和为: {count} </h2>
                    <button onClick={this.add}>点我+1</button>
                    <button onClick={this.death}>卸载组件</button>
                    <button onClick={this.force}>不更改任何状态中的数据强制更新</button>
                </div>
            )
        }
    }

    ReactDOM.render(<Sum count={100} />, document.getElementById("test"));
</script>
</body>
</html>